package com.nbsaas.boot.filter;

import com.nbsaas.boot.thread.TenantContext;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import java.io.IOException;

@Component
public class TenantFilter implements Filter {

    private static final String TENANT_HEADER = "X-Tenant-ID";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        try {
            HttpServletRequest httpRequest = (HttpServletRequest) request;

            // 1. 优先从请求头读取
            String tenantId = httpRequest.getHeader(TENANT_HEADER);

            // 2. 也可以考虑从参数或域名中提取
            if (tenantId == null || tenantId.isBlank()) {
                tenantId = httpRequest.getParameter("tenant");
            }

            // 3. 默认租户逻辑（可选）
            if (tenantId == null) {
                tenantId = "default";
            }

            // 4. 写入 ThreadLocal
            TenantContext.setTenant(tenantId);

            // 继续执行请求链
            chain.doFilter(request, response);

        } finally {
            // 5. 请求结束清理
            TenantContext.clear();
        }
    }
}
